/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GoLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_01_01			*/
/*	File:		GoUdpTest.go			*/
/********************************************************/

package main

import (
	"os"
	. "GoGlb"
	C "GoCls"
	N "GoNet"
)

func main() {
	if len(os.Args) > 1 {
		server()
	} else {
		client()
	}
}

func server() {
	u := new(N.GoUdp)
	if nil == u.GoUdpListen(N.GO_UP_UDP4, ":12345") {
		for {
			r := make([]byte, GO_KBYTES1)
			_, e := u.GoUdpRecv(r)
			if nil == e {
				GoPrint("%s\n", string(r))
				s := "Server: " + string(r)
				_, e := u.GoUdpSend([]byte(s))
				if nil != e {
					GoPrint("Failed to GoUdpSend\n")
				}
			} else {
				GoPrint("Failed to GoUdpRecv\n")
			}
		}
		u.GoUdpClose()
	} else {
		GoPrint("Failed to GoUdpListen\n")
	}
}

func client() {
	u := new(N.GoUdp)
	s := "Copyright (C) 2016 Gong Li Bin		"
	if nil == u.GoUdpDial(N.GO_UP_UDP4, "127.0.0.1:12345") {
		for i := 0; i < 10; i ++ {
			C.GoTimeSleep(1, 0)
			_, e := u.GoUdpWrite([]byte(s))
			if nil == e {
				r := make([]byte, GO_KBYTES1)
				_, e := u.GoUdpRecv(r)
				if nil == e {
					GoPrint("%s\n", string(r))
				} else {
					GoPrint("Failed to GoUdpRecv\n")
				}
			} else {
				GoPrint("Failure to GoUdpSend\n")
			}
		}
		u.GoUdpClose()
	} else {
		GoPrint("Failed to GoUdpDial\n")
	}
}
